import React, { Component, Fragment } from 'react'
import { Button, Card, Table, Modal } from 'antd';
import { message } from 'antd';

import Linkbutton from '../../components/link-button'
import { getcategory, addcategory, updatecategory } from '../../api/index'

import Addfrom from './addfrom'
import Editfrom from './eidtfrom';



export default class index extends Component {
  state = {
    loading: true,
    visible: 0,
    dataSource: [],
    dataSource2: [],
    parentId: 0,
    parentName: '',
    prvname: '',
    _id: '',
  }

  addfrom = React.createRef();
  editfrom = React.createRef();
  columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      // key: 'name',
      width: '70%'
    },
    {
      title: '操作',
      // dataIndex: '',
      key: 'lock',
      render: (data) => <Fragment><Linkbutton onClick={this.showupdateModal(data)}>修改分类名称</Linkbutton>&nbsp;
        {
          this.state.parentId === 0 ? <Linkbutton onClick={this.showdataSource2(data)}>查看分类</Linkbutton> : null
        }
      </Fragment>
    },
  ];

  onFinishFailed = (errorInfo) => {
    message.error(errorInfo)
  };
  getcategorys = async () => {
    this.setState({ loading: true });
    const result = await getcategory(this.state.parentId)
    if (result.status === 0) {
      if (this.state.parentId === 0) {
        this.setState({ dataSource: result.data, loading: false })
      } else {
        this.setState({ dataSource2: result.data, loading: false })
      }

    } else {
      message.error('获取失败')
    }
  }
  showdataSource2 = (data) => {
    return () => {
      this.setState({ parentId: data._id, parentName: data.name },
        this.getcategorys
      )
    }
  }
  showaddModal = () => {
    this.setState({
      visible: 1,
    });
  };
  showupdateModal = (data) => {
    return () => {
      this.setState({ visible: 2, _id: data._id, prvname: data.name });
    }

  };
  adddata = async () => {
    try {
      const fieldsValue = await this.addfrom.current.validateFields();
      const result = await addcategory(fieldsValue.parentId, fieldsValue.parentName)
      if (result.status === 0) {
        message.success('添加成功', 2)
        if (result.data.parentId === '0') {
          this.setState({ dataSource: [...this.state.dataSource, result.data] })
        } else {
          this.setState({ dataSource2: [...this.state.dataSource2, result.data] })
        }
        this.setState({ visible: 0 })
      } else {
        message.error('添加失败', 2)
      }
    } catch (error) {
      message.error(error)
    }
  }
  updatedata = async () => {
    try {
      const fieldsValue = await this.editfrom.current.validateFields();
      const result = await updatecategory(this.state._id, fieldsValue.parentName)
      if (result.status === 0) {
        message.success('修改成功', 2)
        if (this.state.parentId === 0) {
          const newdata = this.state.dataSource.map((item) => {
            if (item._id === this.state._id) {
              item.name = fieldsValue.parentName
            }
            return item
          })
          this.setState({ dataSource: newdata })
        } else {
          const newdata = this.state.dataSource2.map((item) => {
            if (item._id === this.state._id) {
              item.name = fieldsValue.parentName
            }
            return item
          })
          this.setState({ dataSource2: newdata })
        }
        this.setState({ visible: 0 })
      } else {
        message.error('修改失败', 2)
      }
    } catch (error) {
      message.error(error, 2)
    }
  }
  handleCancel = () => {
    this.setState({ visible: 0 });
  };
  back0 = () => {
    this.setState({
      parentId: 0,
      parentName: '',
      dataSource2:[]
    })
  }
  componentDidMount() {
    this.getcategorys()
  }
  render() {
    const extra = (
      <Button type='primary' onClick={this.showaddModal}>+ 添加</Button>
    )
    const title = '一级分类列表'
    const { parentName, loading, visible, dataSource, dataSource2, parentId, prvname, _id } = this.state
    return (
      <Fragment>
        <Card style={{ height: '100%', overflow: 'auto' }}
          title={parentId === 0 ? title : (
          <Fragment>
            <Linkbutton onClick={this.back0} >{title}</Linkbutton>
            <span>--&gt;{parentName}</span>
          </Fragment>
        )} extra={extra} >
          <Table pagination={{
            responsive: false, defaultPageSize: 9,
            showQuickJumper: { goButton: (<Fragment>&nbsp;&nbsp;<Button type='primary'>跳转</Button></Fragment>) }
          }}
            rowKey='_id' bordered dataSource={parentId === 0 ? dataSource : dataSource2}
            columns={this.columns} loading={loading}
          />
        </Card>
        <Modal title='添加商品分类' visible={visible === 1}
          onCancel={this.handleCancel} onOk={this.adddata} destroyOnClose >
          <Addfrom addfrom={this.addfrom} parentId={parentId}
            dataSource={dataSource} adddata={this.adddata} />
        </Modal>
        <Modal title='修改商品分类' visible={visible === 2}
          onCancel={this.handleCancel} onOk={this.updatedata} destroyOnClose>
          <Editfrom editfrom={this.editfrom} prvname={prvname} _id={_id}
            parentName={parentName} updatedata={this.updatedata}/>
        </Modal>
      </Fragment>
    )
  }
}
